#pragma once

#include <unistd.h>
#include <mutex>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include <cstring>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define BACKLOG 6

class TcpServer
{
private:
    TcpServer(const int port)
        : _port(port), _listen_sock(-1)
    {
    }
    ~TcpServer()
    {
        if (_listen_sock > 0)
        {
            close(_listen_sock);
        }
    }

public:
    static TcpServer *get_instance(int port)
    {
        if (_svr == nullptr)
        {
            _mtx.lock();
            if (_svr == nullptr)
            {
                _svr = new TcpServer(port);
                _svr->Init();
            }
            _mtx.unlock();
        }
        return _svr;
    }
    int sock()
    {
        return _listen_sock;
    }

private:
    void Init()
    {
        Socket();
        Bind();
        Listen();
        ILOG("TcpServer init success");
    }
    void Socket()
    {
        _listen_sock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listen_sock < 0)
        {
            ELOG("_listen_sock init error!");
            exit(1);
        }
        int opt = 1; // 设置端口复用
        setsockopt(_listen_sock, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        ILOG("create _listen_sock success");
    }
    void Bind()
    {
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(_listen_sock, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            ELOG("bind _listen_sock error!");
            exit(2);
        }
        ILOG("bind _listen_sock success");
    }
    void Listen()
    {
        if (listen(_listen_sock, BACKLOG) < 0)
        {
            ELOG("_listen_sock listen error!");
            exit(3);
        }
        ILOG("_listen_sock listen success");
    }

private:
    int _port;
    int _listen_sock;
    static TcpServer *_svr;
    static std::mutex _mtx;
};

TcpServer *TcpServer::_svr = nullptr;
std::mutex TcpServer::_mtx;